<?php

declare(strict_types=1);
// +----------------------------------------------------------------------
// | swiftAdmin 极速开发框架 [基于WebMan开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2030 http://www.swiftadmin.net
// +----------------------------------------------------------------------
// | swiftAdmin.net High Speed Development Framework
// +----------------------------------------------------------------------
// | Author: meystack <coolsec@foxmail.com> Apache 2.0 License
// +----------------------------------------------------------------------
namespace app\admin\controller\system;


use app\AdminController;
use app\common\library\Ip2Region;
use app\common\model\system\Putorder as Putorders;
use app\common\model\system\ProductLog;
use app\common\model\system\PutorderProduct;
use app\common\model\system\User as UserModel;
use app\common\model\system\Product;
use think\facade\Db;
use support\Response;
use system\Random;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Webman\Http\Request;

/**
 * 用户管理
 * Class User
 * @package app\admin\controller\system
 */
class Putorder extends AdminController
{
    // 初始化函数
    public function __construct()
    {
        parent::__construct();
        $this->model = new Putorders();
    }
    protected $config = [
        'statusArr' => [
            1 => '已下单',
            2 => '已确认',
            3 => '已分配',
            4 => '配送中',
            5 => '确认送达',
            6 => '已完成',
            7 => '已取消',
        ],
        'sendType' => [
            1 => '公司配送',
            2 => '自提',
            3 => '货拉拉',
            4 => '挂车'
        ]
    ];
    /**
     * 获取资源
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): \support\Response
    {

        if (request()->isAjax()) {
            // 获取数据
            $post = \request()->all();
            $page = (int)input('page') ?? 1;
            $limit = (int)input('limit') ?? 10;
            // 生成查询条件
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['name|mobile|send_mobile', 'like', '%' . $post['title'] . '%'];
            }
            $count = $this->model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $this->model->where($where)->order("id desc")->limit((int)$limit)->page((int)$page)->select();
            foreach ($list as $row) {
                $row['put_name'] = '';
                $row['put_mobile'] = '';
                $user = (new UserModel())->where('id', $row['user_id'])->find();
                if ($user) {
                    $row['put_name'] = $user['name'];
                    $row['put_mobile'] = $user['mobile'];
                }
                if ($row['send_type'] == 1) {
                    $ouser = (new UserModel())->where('id', $row['ouser_id'])->find();
                    $row['send_name'] = $ouser['name'] ?? '';
                    $row['send_mobile'] = $ouser['mobile'] ?? '';
                } else {
                    $row['send_name'] = $this->config['sendType'][$row['send_type']] ?? '';
                    $row['send_mobile'] = $row['send_mobile'] ?? '';
                }
                $row['send_text'] = $this->config['sendType'][$row['send_type']] ?? '未分配';
                $row['status_text'] = $this->config['statusArr'][$row['status']] ?? '未知状态';
                $row['addjson'] = json_decode($row['addjson'] ?? '', true);
                $row['addcount'] = count($row['addjson'] ?? []);
            }
            // TODO..
            return $this->success('查询成功', "", $list, $count);
        }
        $user1 = (new UserModel())->where(['type' => [3]])->field('id,name,mobile')->select();
        $user2 = (new UserModel())->where(['type' => [1, 2]])->field('id,name,mobile')->select();
        return view('/system/putorder/index', ['user1' => $user1, 'user2' => $user2]);
    }

    /**
     * 删除轮播图
     */
    public function del()
    {
        $id = input('id');
        if (!empty($id) && is_numeric($id)) {
            $order = $this->model->where('id', $id)->find();
            if (empty($order)) {
                return $this->error('订单不存在！');
            }
            Db::startTrans();
            try {
                $this->model::destroy($id);
                if ($order['status'] >= 2) {
                    $products = (new PutorderProduct())->where('orderid', $order['id'])->select();
                    foreach ($products as $product) {
                        if ($order['type'] == 1) {
                            (new ProductLog())->ProductSkuEdit($product['goodsid'], $product['number'], 1, '订单' . $order['id'] . '取消返还库存', 0);
                        } else {
                            (new ProductLog())->ProductSkuEdit($product['goodsid'], -$product['number'], 1, '退单类型订单' . $order['id'] . '取消扣除库存', 0);
                        }
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('删除成功！');
        }
        return $this->error('删除失败，请检查您的参数！');
    }

    /**
     * 编辑会员
     */
    public function edit()
    {
        $id = input('id');
        if (request()->isPost()) {
            $post = \request()->post();
            $post['images'] = [];
            $post['album'] = $post['album'] ?? [];
            foreach ($post['album'] as $value) {
                $post['images'][]['url'] = $value['src'];
            }
            $post['images'] = json_encode($post['images']);
            // 查询数据
            $data = $this->model->find($post['id']);
            if (empty($data)) {
                return $this->error('订单不存在');
            }
            if ($data['status'] == 6 || $data['status'] == 7) {
                return $this->error('已完成或取消订单不可操作');
            }
            $latlon =  explode(',', $post['latlon']);
            if (count($latlon) != 2) {
                return $this->error('坐标参数错误,请重试');
            }
            $post['lat'] = $latlon[1];
            $post['lon'] = $latlon[0];
            if ($post['getstatus'] > 2 && $post['getstatus'] < 7 && empty($post['send_type'])) {
                return $this->error('请选择配送方式');
            }
            if (!empty($post['send_type'])) {
                switch ($post['send_type']) {
                    case '1':
                        if (empty($post['ouser_id'])) {
                            return $this->error('请选择配送人员');
                        }
                        $post['send_mobile'] = '';
                        break;

                    default:
                        if (empty($post['send_mobile'])) {
                            return $this->error('请填写配送联系信息');
                        }
                        $post['ouser_id'] = 0;
                        break;
                }
            }
            if (!empty($post['getstatus']) && $data['status'] != $post['status']) {
                switch ($post['status']) {
                        //订单确认
                    case '2':
                        $post['confirm_time'] = time();
                        break;
                    case '3':
                        $post['allocate_time'] = time();
                        break;
                    case '4':
                        $post['pickup_time'] = time();
                        break;
                    case '5':
                        $post['delivery_time'] = time();
                        break;
                    case '6':
                        $post['complete_time'] = time();
                        break;
                    case '7':
                        $post['cacel_time'] = time();
                        break;
                    default:
                        break;
                }
            }
            Db::startTrans();
            try {
                if (!empty($post['getstatus']) && $data['status'] != $post['getstatus']) {
                    $products = (new PutorderProduct())->where('orderid', $data['id'])->select();
                    //未确认订单操作
                    if ($data['status'] <= 1  && $post['getstatus'] > 1 && $post['getstatus'] < 7) {
                        foreach ($products as $product) {
                            if ($data['type'] == 1) {
                                (new ProductLog())->ProductSkuEdit($product['goodsid'], -$product['number'], 1, '订单' . $data['id'] . '确认扣除库存', 0);
                            } else {
                                (new ProductLog())->ProductSkuEdit($product['goodsid'], $product['number'], 1, '订单' . $data['id'] . '退单确认增加库存', 0);
                            }
                        }
                    }
                    //已确认订单取消操作
                    if ($data['status'] > 1  && $post['getstatus'] == 7) {
                        foreach ($products as $product) {
                            if ($data['type'] == 1) {
                                (new ProductLog())->ProductSkuEdit($product['goodsid'], $product['number'], 1, '订单' . $data['id'] . '取消返还库存', 0);
                            } else {
                                (new ProductLog())->ProductSkuEdit($product['goodsid'], -$product['number'], 1, '退单类型订单' . $data['id'] . '取消扣除库存', 0);
                            }
                        }
                    }
                    $post['status'] = $post['getstatus'];
                }
                $this->model->update($post);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('更新成功！');
        }
        $data = $this->model->find($id);
        if ($data) {
            $data['status_text'] = $this->config['statusArr'][$data['status']] ?? '未知状态';
            $data['images'] = json_decode($data['images'] ?? '', true) ?? [];
            $data['latlon'] = $data['lon'] . ',' . $data['lat'];
        }
        $user1 = (new UserModel())->where(['type' => [2, 3]])->field('id,name,mobile')->select();
        $user2 = (new UserModel())->where(['type' => [1, 2]])->field('id,name,mobile')->select();
        return view('/system/putorder/add', [
            'data' => $data,
            'user1' => $user1,
            'user2' => $user2,
            'statusArr' => $this->config['statusArr']
        ]);
    }

    /**
     * 编辑会员
     */
    public function look()
    {
        $id = input('id');
        $data = $this->model->find($id);
        if ($data) {
            $data['type_text'] = $data['type'] == 1 ? '下单' : '退单';
            $data['status_text'] = $this->config['statusArr'][$data['status']] ?? '未知状态';
            $data['images'] = json_decode($data['images'] ?? '', true) ?? [];
            $data['addjson'] = json_decode($data['addjson'] ?? '', true) ?? [];
            //销售员信息
            $data['put_name'] = '';
            $data['put_mobile'] = '';
            $user = (new UserModel())->where('id', $data['user_id'])->find();
            if ($user) {
                $data['put_name'] = $user['name'];
                $data['put_mobile'] = $user['mobile'];
            }
            $data['send_name'] = '';
            if ($data['send_type'] == 1) {
                $ouser = (new UserModel())->where('id', $data['ouser_id'])->find();
                $data['send_name'] = $ouser['name'] ?? '';
                $data['send_mobile'] = $ouser['mobile'] ?? '';
            } else {
                $data['send_name'] = $this->config['sendType'][$data['send_type']] ?? '未分配';
            }
            $product = (new PutorderProduct())->where('orderid', $data['id'])
                ->select()->each(function ($item) {
                    $item['images'] = json_decode($item['images'], true);
                    return $item;
                });
            $data['orderproduct'] = $product;
        }
        return view('/system/putorder/look', [
            'data' => $data
        ]);
    }


    /**
     * 获取资源
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function goods(): \support\Response
    {

        if (request()->isAjax()) {
            // 获取数据
            $post = \request()->all();
            $page = (int)input('page') ?? 1;
            $limit = (int)input('limit') ?? 10;
            // 生成查询条件
            $where = array();
            $id = $post['id'] ?? 0;
            $where[] = ['orderid', '=', $id];
            $count = (new PutorderProduct())->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = (new PutorderProduct())->where($where)->order("id desc")->limit((int)$limit)->page((int)$page)->select();
            foreach ($list as $row) {
                $row['images'] = json_decode($row['images'], true);
            }
            // TODO..
            return $this->success('查询成功', "", $list, $count);
        }
        return view('/system/putorder/goods', []);
    }



    /**
     * 删除轮播图
     */
    public function goodsdel()
    {
        $id = input('id');
        if (!empty($id) && is_numeric($id)) {
            $orderproduct = (new PutorderProduct())->where('id', $id)->find();
            if (empty($orderproduct)) {
                return $this->error('订单商品不存在！');
            }
            $haveorder = (new PutorderProduct())->where('orderid', $orderproduct['orderid'])->count();
            if ($haveorder <= 1) {
                return $this->error('订单商品必须有一种，如确认删除请删除或取消订单！');
            }
            $order = $this->model->where('id', $orderproduct['orderid'])->find();
            if (empty($order)) {
                return $this->error('关联订单不存在');
            }
            if ($order['status'] >= 6) {
                return $this->error('订单状态不可操作');
            }
            Db::startTrans();
            try {
                PutorderProduct::destroy($id);
                //库存操作
                if ($order['status'] >= 2) {
                    $update = [
                        'id' => $order['id'],
                        'total' => $order['total'] - ($orderproduct['number'] * $orderproduct['price'])
                    ];
                    $this->model->update($update);
                    if ($order['type'] == 1) {
                        (new ProductLog())->ProductSkuEdit($orderproduct['goodsid'], $orderproduct['number'], 1, '删除商品' . $orderproduct['id'] . '返还库存', 0);
                    } else {
                        (new ProductLog())->ProductSkuEdit($orderproduct['goodsid'], -$orderproduct['number'], 1, '退单类型删除商品' . $orderproduct['id'] . '扣除库存', 0);
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('删除成功！');
        }
        return $this->error('删除失败，请检查您的参数！');
    }

    /**
     * 编辑会员
     */
    public function goods_edit()
    {
        $id = input('id');
        if (request()->isPost()) {
            $post = \request()->post();
            $orderproduct = (new PutorderProduct())->where('id', $post['id'])->find();
            if (empty($orderproduct)) {
                return $this->error('订单商品不存在！');
            }
            $post['number'] = (int)($post['number'] ?? 0);
            if ($orderproduct['number'] == $post['number']) {
                return $this->error('商品数量没有改变');
            }
            if ($post['number'] <= 0) {
                return $this->error('商品数量不能为0');
            }
            $order = $this->model->where('id', $orderproduct['orderid'])->find();
            if (empty($order)) {
                return $this->error('关联订单不存在');
            }
            if ($order['status'] >= 6) {
                return $this->error('订单状态不可操作');
            }
            //变更金额
            $bgnumber = $post['number'] - $orderproduct['number'];
            $bgtotal = $bgnumber * $orderproduct['price'];
            $update = [
                'id' => $order['id'],
                'total' => $order['total'] + $bgtotal
            ];
            Db::startTrans();
            try {
                $this->model->update($update);
                (new PutorderProduct())->update(['id' => $orderproduct['id'], 'number' => $post['number']]);
                //变更库存
                if ($order['status'] > 1) {
                    if ($order['type'] == 1) {
                        (new ProductLog())->ProductSkuEdit($orderproduct['goodsid'], -$bgnumber, 1, '变更商品数量' . $orderproduct['id'] . '更改库存', 0);
                    } else {
                        (new ProductLog())->ProductSkuEdit($orderproduct['goodsid'], $bgnumber, 1, '变更商品数量' . $orderproduct['id'] . '更改库存', 0);
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('更新成功！');
        }
        $data = (new PutorderProduct())->find($id);
        return view('/system/putorder/goods_edit', [
            'data' => $data,
            'product' => (new Product())->select()
        ]);
    }

    /**
     * 编辑会员
     */
    public function goods_add()
    {
        $id = input('id');
        if (request()->isPost()) {
            $post = \request()->post();
            $post['number'] = (int)($post['number'] ?? 0);
            if ($post['number'] <= 0) {
                return $this->error('商品数量不能为0');
            }
            $order = $this->model->where('id', $post['id'])->find();
            if (empty($order)) {
                return $this->error('关联订单不存在');
            }
            if ($order['status'] >= 6) {
                return $this->error('订单状态不可再添加商品');
            }
            //查询该商品是否已添加 直接去修改数量
            $haveoproduct = (new PutorderProduct())->where(['goodsid' => $post['goodsid'], 'orderid' => $post['id']])->find();
            if (!empty($haveoproduct)) {
                return $this->error('该订单当前产品已添加');
            }
            $product = (new Product())->field('id,title,series,types,images,price,codes,spec,remark,stock,detail')->where('id', $post['goodsid'])->find();
            if (empty($product)) {
                return $this->error('产品不存在');
            }
            $product = $product->toArray();
            //变更金额
            $update = [
                'id' => $order['id'],
                'total' => $order['total'] + ($product['price'] * $post['number'])
            ];
            $product['number'] = $post['number'];
            $product['goodsid'] = $product['id'];
            $product['orderid'] = $order['id'];
            unset($product['id']);
            Db::startTrans();
            try {
                $this->model->update($update);
                (new PutorderProduct())->create($product);
                //变更库存
                if ($order['status'] > 1) {
                    if ($order['type'] == 1) {
                        (new ProductLog())->ProductSkuEdit($product['goodsid'], -$post['number'], 1, '订单添加商品数量' . $order['id'] . '更改库存', 0);
                    } else {
                        (new ProductLog())->ProductSkuEdit($product['goodsid'], $post['number'], 1, '订单添加商品' . $order['id'] . '更改库存', 0);
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('更新成功！');
        }
        return view('/system/putorder/goods_add', [
            'id' => $id,
            'product' => (new Product())->select()
        ]);
    }
}
